﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace LINQToolKit.Query
{
    public sealed class UriEqualityComparer : IEqualityComparer<string>
    {
        public bool Equals(string x, string y)
        {
            string regx = @"(?<uri>\w{4}s?:\/\/[^\?]+)\?*(?<query>.*)";
            var xmatch = Regex.Match(x, regx);
            var ymatch = Regex.Match(y, regx);

            if (xmatch.Success && ymatch.Success &&
                xmatch.Groups.Count == ymatch.Groups.Count)
            {
                // comparing the uri part
                if (xmatch.Groups[1].Value.Equals(ymatch.Groups[1].Value))
                {
                    // comparing the query string part
                    var xquery = xmatch.Groups[2].Value.TrimEnd('&').Split('&');
                    var yquery = ymatch.Groups[2].Value.TrimEnd('&').Split('&');

                    if (xquery.Length == yquery.Length)
                    {
                        foreach (var xq in xquery)
                        {
                            bool found = false;

                            foreach (var yq in yquery)
                            {
                                if (xq.Equals(yq))
                                {
                                    found = true;
                                }
                            }

                            if (!found)
                            {
                                return false;
                            }
                        }

                        return true;
                    }
                }
            }

            return false;
        }

        public int GetHashCode(string obj)
        {
            return obj.GetHashCode();
        }
    }
}
